package enduringLink;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class RequestHandler extends ChannelInboundHandlerAdapter {

    private static Channel channel;
    Dispatcher dis;
    public RequestHandler(Dispatcher dis){
        this.dis = dis;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(channel == null)
            channel = ctx.channel();
        MyContent myContent = (MyContent) msg;
        ctx.executor().execute(new Runnable() {
            @Override
            public void run() {
                String serviceName = myContent.getName();
                String method = myContent.getMethodName();
                Object c = dis.get(serviceName);
                Class<?> clazz = c.getClass();
                try {
                    Method m = clazz.getMethod(method, myContent.getParameterTypes());
                    m.invoke(c, myContent.getArgs());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static Channel getChannel(){
        return channel;
    }
}
